package com.google.code.hostsman;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;

import com.google.code.hostsman.db.DomainIPPair;

public class NewEntryDialogFragment extends DialogFragment {
	public interface NewEntryDialogListener {
		public void onDialogEntryAdd(DialogFragment dialog, DomainIPPair pair);
	}

	private NewEntryDialogListener listener;

	public Dialog onCreateDialog(Bundle savedInstanceState) {

		LayoutInflater inflater = getActivity().getLayoutInflater();

		final View layout=inflater.inflate(R.layout.dialog_new_entry, null);
		
		// Use the Builder class for convenient dialog construction
		AlertDialog.Builder builder = new AlertDialog.Builder(getActivity())
				.setView(layout)
				.setTitle(R.string.pairs_add)
				.setPositiveButton(android.R.string.ok,
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int id) {
								EditText domainEdit = (EditText) layout
										.findViewById(R.id.domain);
								EditText ipEdit = (EditText) layout
										.findViewById(R.id.ip);
								
								DomainIPPair pair=new DomainIPPair();
								pair.setDomain(domainEdit.getText().toString());
								pair.setIp(ipEdit.getText().toString());
								
								listener.onDialogEntryAdd(
										NewEntryDialogFragment.this, pair);
							}
						})
				.setNegativeButton(android.R.string.cancel,
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int id) {
							}
						});

		return builder.create();
	}

	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		// Verify that the host activity implements the callback interface
		try {
			// Instantiate the NoticeDialogListener so we can send events to the
			// host
			listener = (NewEntryDialogListener) activity;
		} catch (ClassCastException e) {
			// The activity doesn't implement the interface, throw exception
			throw new ClassCastException(activity.toString()
					+ " must implement "+NewEntryDialogListener.class.getName());
		}
	}
}
